package org.example.skytool.commom;

/**
 * @author 22449
 */
public class StringUtil {


    /**
     * 判断两个字符串是不是子串
     *
     * @param father
     * @param kid
     * @return
     */
    public static boolean isKid(String father, String kid) {
        int kidLength = kid.length();
        int fatherLength = father.length();
        //求next数组
        int[] next = new int[kidLength];
        next[0] = -1;
        //i为next的值
        //j为字符串索引
        for (int i = -1, j = 0; j < kidLength-1; ) {
            if (i == -1 || kid.charAt(i) == kid.charAt(j)) {
                i++;
                j++;
                next[j] = i;
            }else{
                i = next[i];
            }
        }
        //记录子串数组索引
        int index1 = 0;
        //进行匹配
        for (int i = 0; ; ) {
            if (index1 == kidLength) {
                return true;
            }
            if (i == fatherLength) {
                return false;
            }
            if (father.charAt(i) == kid.charAt(index1)) {
                index1++;
                i++;
            } else {
                index1 = next[index1];
            }
            if (index1 == -1) {
                i++;
                index1++;
            }
        }
    }

    /**
     * 给你两个字符串 father 和 kid ，
     * 请你在 father 字符串中找出 kid 字符串的第一个匹配项的下标
     * （下标从 0 开始）。如果 kid 不是 father 的一部分，则返回  -1 。
     *
     * @param father
     * @param kid
     * @return
     */
    public static int strStr(String father, String kid) {
        int kidLength = kid.length();
        int fatherLength = father.length();
        //求next数组
        int[] next = new int[kidLength];
        next[0] = -1;
        //i为next的值
        //j为字符串索引
        for (int i = -1, j = 0; j < kidLength-1; ) {
            if (i == -1 || kid.charAt(i) == kid.charAt(j)) {
                i++;
                j++;
                next[j] = i;
            }else{
                i = next[i];
            }
        }
        //记录子串数组索引
        int index1 = 0;
        //进行匹配
        for (int i = 0; ; ) {
            if (index1 == kidLength) {
                return i - index1;
            }
            if (i == fatherLength) {
                return -1;
            }
            if (father.charAt(i) == kid.charAt(index1)) {
                index1++;
                i++;
            } else {
                index1 = next[index1];
            }
            if (index1 == -1) {
                i++;
                index1++;
            }
        }
    }

    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str){
       return str == null || "".equals(str);
    }



}
